#include "device_info.h"

void drop_enter (char  *str)
{
    while (*str !='\0')
    {
        /* code */
        if  (*str == '\n') {
            *str = '\0';
            break;
        }
        str++;
    }
    
}

void exec_script_string(char *script, char *res){
    FILE *fd;
    char result[20];
    fd = popen(script, "r");
    fgets(result, sizeof(result),fd);
    pclose(fd);
    drop_enter(result);
    strcpy(res, result);
}
int exec_script_int(char *script){
    FILE *fd;
    int res;
    char result[20];
    fd = popen(script, "r");
    fgets(result, sizeof(result),fd);
    pclose(fd);
    sscanf(result, "%d", &res);
    return res;
}
float exec_script_float(char *script){
    FILE *fd;
    float res;
    char result[20];
    fd = popen(script, "r");
    fgets(result, sizeof(result),fd);
    pclose(fd);
    sscanf(result, "%f", &res);
    return res;
}

/**
 * 获取Wan口网关地址
 */
void getDeviceGateway(char *gateway_ip){
    exec_script_string("sh /bin/network_info.sh 4", gateway_ip);
}

/**
 * 获取Wan口地址
 */
void getDeviceIp(char *wan_ip){
    exec_script_string("sh /bin/network_info.sh 1",wan_ip);
}

void getDeviceMask(char *mask_ip){
    exec_script_string("sh /bin/network_info.sh 3",mask_ip);
}

void getDeviceMac(char *wan_mac){
    exec_script_string("sh /bin/network_info.sh 2",wan_mac);
    
}

int tx_bytes() {
    return exec_script_int("sh /bin/neiwang_tx_rx 2");
}
int rx_bytes() {
    return exec_script_int("sh /bin/neiwang_tx_rx 1");
}
float getCpuUsage(){
    
    FILE *fd;
    float cpu;
    char cpuUage[10];
    fd = popen("uptime | awk '{print $8}' | cut -f 1 -d ','", "r");
    fgets(cpuUage, sizeof(cpuUage),fd);
    pclose(fd);
    sscanf(cpuUage, "%f", &cpu);
    printf("cpu:%f\n", cpu);
    return cpu;
}
int get_total_memory(){
    return exec_script_int("sh /bin/device_info.sh 1");
}
int get_free_memory(){
    return exec_script_int("sh /bin/device_info.sh 2");
}